package commands;

import user.Admin;
import user.User;
import messages.*;
import core.UserManager;
import event.*;
import game.Player;


/**
 * The AccountEdit command.
 * 
 * This command will handle AccountEdit messages.
 */
public class AccountEditCommand extends Command {

	
	public AccountEditCommand(Message message, User user) {
		super(message, user);
	}
	
	
	@Override
	public void execute() {
		UserManager userManager = controller.getUserManager();
		AccountEditMessage message = (AccountEditMessage) this.message;
		message.setSenderLogin(this.user.getLogin());
		
		String login = message.getLogin();
		String newPassword = message.getNewPassword();
		String newRole = message.getNewRole();
		
		synchronized(userManager) {
			AccountEditionFailedMessage.ErrorCode errorCode = null;
			
			// If the login is invalid or both newPassword and newRole are invalid or newRole is an invalid role...
			if (login == null || login == "" || ((newPassword == null || newPassword.isEmpty()) && (newRole == null || newRole.isEmpty())) || (newRole != null && !User.isValidRole(newRole))) {
				errorCode = AccountEditionFailedMessage.ErrorCode.InvalidParameters;
			}
			// If the user is just a regular user and he is trying to edit an account other than his own or if he his trying to become Admin...
			else if (!(this.user instanceof Admin)) {				
				if (!user.getLogin().equals(login) || (newRole != null && !newRole.equals(user.getPlayer().getRole())))
					errorCode = AccountEditionFailedMessage.ErrorCode.InsufficientPermissions;
			}
							
			else if (userManager.isLoginAvailable(login)) {
				errorCode = AccountEditionFailedMessage.ErrorCode.UnknownUser;
			}
			
			if (errorCode != null) {
				controller.fireAccountEditionFailedEvent(new AccountEditionFailedEventArgs(
						this.user.getLogin(), new AccountEditionFailedMessage(message, errorCode)));
				
				return;
			}
			
			Player player = userManager.getPlayer(login);
			
			if (newPassword != null && !newPassword.isEmpty())
				player.setPassword(newPassword);
			
			if (newRole != null && !newRole.isEmpty())
				player.setRole(newRole);
			
			userManager.saveKnownUsers();
		}
		
		controller.fireAccountEditionSuccessful(new AccountEditionSuccessfulEventArgs(
				this.user.getLogin(), new AccountEditionSuccessfulMessage(this.user.getLogin(), login)));
	}
}
